<template>
  <div class="address-manager">
    <!-- 顶部操作栏 -->
    <div class="action-header">
      <!-- <h2 class="title">{{ $t('user.addressManagement') }}</h2> -->
      <div class="action-buttons">
        <!-- <span class="address-count">{{ $t("user.haveCreatedAddress", { num: userAddressList.length }) }}</span> -->
        <Button type="primary" @click="addCreateMet" icon="md-add" class="add-button">
          {{ $t("user.addedShippingAddress") }}
        </Button>
      </div>
    </div>

    <Table :columns="columns" :data="userAddressList">
      <template slot-scope="{ row }" slot="addressDetail">
        <div class="address-detail">{{ row.addressDetail }} {{ row.areaText ? row.areaText + "," : "" }}
          {{ row.cityText ? row.cityText + "," : "" }}
          {{ row.provinceText }},{{ row.countryText }}</div>

        <div style="font-size: 14px;" class="address-phone">+{{ row.regionCode }} {{ row.mobile }}
        </div>
      </template>
      <template slot-scope="{ row }" slot="action">
        <div class="address-actions">
          <Button type="text" @click="edit(row)">
            {{ $t("user.edit") }}
          </Button>
          <Button type="text" @click="onDelete(row.id)">
            {{ $t("user.delete") }}
          </Button>
          <Button type="text" @click="onCopy(row)">
            {{ $t("user.copy") }}
          </Button>
          <Button v-if="!row.isDefault" type="text" @click="onSetAddressDefault(row.id)">
            {{ $t("user.setDefault") }}
          </Button>

          <span v-if="row.isDefault" class="default-tag">
            {{ $t("user.defaultAddress") }}
          </span>
        </div>
      </template>
    </Table>

    <!-- 新增/编辑地址弹窗 -->
    <create-user-address ref="createRef" @updateMet="getAddressList"></create-user-address>

    <!-- 地址表单弹窗 -->
    <Modal v-model="showPop" :title="formValidate.id ? $t('user.editShippingAddress') : $t('user.addedShippingAddress')"
      class="address-modal" width="700" :mask-closable="false" @on-cancel="hidePop">
      <div class="modal-content">
        <Form v-if="showPop" ref="formValidate" :label-width="100" :model="formValidate" :rules="ruleValidate">
          <!-- 姓名部分 -->
          <Row :gutter="24">
            <Col span="12">
            <FormItem :label="$t('user.name')" prop="name">
              <Input v-model="formValidate.name" :placeholder="$t('personal.FirstName')" size="large"></Input>1
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem :label="$t('personal.LastName')" prop="surname">
              <Input v-model="formValidate.surname" :placeholder="$t('personal.LastName')" size="large"></Input>
            </FormItem>
            </Col>
          </Row>

          <!-- 地址部分 -->
          <FormItem :label="$t('user.locationAddress')" prop="countryCode">
            <Select v-model="formValidate.countryCode" @on-change="onCountry" size="large" filterable>
              <Avatar v-if="currentCountryImage" :src="currentCountryImage" slot="prefix" size="small" />
              <Option v-for="item in countryList" :value="item.code" :label="item.text" :key="item.code">
                <div class="country-option">
                  <img v-if="item.flagImg" class="flag" :src="item.flagImg" alt="" />
                  <span>{{ item.text }}</span>
                </div>
              </Option>
            </Select>
          </FormItem>

          <Row :gutter="24">
            <Col span="12">
            <FormItem :label="$t('user.province')" prop="provinceCode">
              <Select :disabled="!formValidate.countryCode" :label-in-value="true" @on-change="onSelectProvince"
                v-model="formValidate.provinceCode" size="large" :placeholder="$t('user.pleaseSelect')">
                <Option v-for="item in provinceList" :value="item.pid" :key="item.id">
                  {{ item.nameLocal }}
                </Option>
              </Select>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem :label="$t('user.city')" :prop="cityList.length == 0 ? '' : 'cityCode'">
              <Select :disabled="!formValidate.provinceCode || cityList.length == 0" :label-in-value="true"
                @on-change="onSelectCity" v-model="formValidate.cityCode" size="large"
                :placeholder="$t('user.pleaseSelect')">
                <Option v-for="item in cityList" :value="item.id" :key="item.id">
                  {{ item.nameLocal }}
                </Option>
              </Select>
            </FormItem>
            </Col>
          </Row>

          <FormItem :label="$t('user.area')">
            <Input v-model="formValidate.areaText" size="large" :disabled="!formValidate.cityCode"
              :placeholder="$t('user.area')"></Input>
          </FormItem>

          <!-- 详细地址 -->
          <FormItem :label="$t('user.detailedAddress')" prop="addressDetail">
            <Input v-model="formValidate.addressDetail" type="textarea" size="large"
              :autosize="{ minRows: 2, maxRows: 5 }" :placeholder="$t('ruleValidate.address_tip')"></Input>
          </FormItem>

          <!-- 联系信息 -->
          <Row :gutter="24">
            <Col span="12">
            <FormItem :label="$t('user.postcode')" prop="postalCode">
              <Input v-model="formValidate.postalCode" size="large" placeholder=""></Input>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem :label="$t('user.mobile')" prop="mobile">
              <Row :gutter="8">
                <Col span="8">
                <Select :label-in-value="true" v-model="formValidate.regionCodeCountry" size="large"
                  :placeholder="$t('user.pleaseSelect')" filterable @on-change="regionChange">
                  <Option v-for="(item, index) in regionCodeList" :label="item.text"
                    :value="item.code + item.regionCountry" :key="item.code + index">
                    <div class="region-option">
                      <img class="region-flag" :src="item.flagImg" alt="" />
                      <span>{{ item.text }}</span>
                    </div>
                  </Option>
                </Select>
                </Col>
                <Col span="16">
                <Input v-model="formValidate.mobile" @on-change="validateInput" maxlength="20" size="large"
                  placeholder=""></Input>
                <span v-if="errorMessage" class="error-message">{{ errorMessage }}</span>
                </Col>
              </Row>
            </FormItem>
            </Col>
          </Row>

          <!-- 默认地址设置 -->
          <FormItem :label="$t('user.defaultAddress')">
            <i-switch v-model="formValidate.isDefault" size="large"></i-switch>
          </FormItem>
        </Form>
      </div>

      <div slot="footer" class="modal-footer">
        <Button @click="hidePop" size="large">{{ $t("user.cancel") }}</Button>
        <Button :loading="loading" v-if="!formValidate.id" @click="onAddressAdd" type="primary" size="large">
          {{ $t("user.confirm") }}
        </Button>
        <Button :loading="loading" v-else @click="onAddressEdit" type="primary" size="large">
          {{ $t("user.edit") }}
        </Button>
      </div>

      <Spin v-if="gloabalLoading" fix>
        <Icon type="ios-loading" size="18" class="loading-icon"></Icon>
        <div>Loading</div>
      </Spin>
    </Modal>
  </div>
</template>

<script>
import CreateUserAddress from "../components/create-user-address.vue";
import { addressAdd, addressEdit, addressList, deleteAddress, setAddressDefault } from "@/api/address";
import { countryAddressList, cityApiList } from "@/api/administrativedivisions";
import { mapState } from "vuex";
import { pointUser } from "@/common/point/api-hook";//打点日志

export default {
  name: "user-addr",
  components: { CreateUserAddress },
  data() {
    return {
      gloabalLoading: false,
      loading: false,
      userAddressList: [],
      showPop: false,
      formValidate: {
        id: "",
        surname: "", // 姓
        name: "", // 名
        addressDetail: "", // 街道地址，详细地址
        areaCode: "", // 区code
        areaText: "", // 区文本
        cityCode: "", // 市code
        cityText: "", // 市文本
        provinceCode: "",
        provinceText: "", // 省份文本
        countryCode: "", // 国家编码
        countryText: "",
        districtCode: "", // 地址编码
        regionCode: "", // 手机国际区号
        regionCodeCountry: "", // 区号+国家
        regionCountry: "", // 区号国家
        isDefault: false, // 是否默认地址
        mobile: "", // 手机号
        phone: "", // 电话
        postalCode: "", // 邮政编码
        recipientName: "", // 收件人姓名
        townText: "", // 文本
      },
      currentCountryImage: "", // 当前国家图片
      cityList: [], // 市区列表
      provinceList: [], //省份市区
      ruleValidate: {
        name: [
          { required: true, message: this.$t("user.pleaseEnter") + this.$t("user.name"), trigger: "blur" },
          { type: 'string', max: 17, message: this.$t('ruleValidate.name'), trigger: 'change' }
        ],
        surname: [
          { required: true, message: this.$t("user.pleaseEnter") + this.$t("personal.LastName"), trigger: "blur" },
          { type: 'string', max: 17, message: this.$t('ruleValidate.name'), trigger: 'change' }
        ],
        addressDetail: [{ required: true, message: this.$t("ruleValidate.address_tip"), trigger: "blur" }],
        postalCode: [{ required: true, message: this.$t("user.pleaseEnter") + this.$t("user.postcode"), trigger: "blur" }],
        mobile: [{ required: true, message: this.$t("user.pleaseEnter") + this.$t("user.mobile"), trigger: "blur" }],
        countryCode: [{ required: true, message: this.$t("user.InputAddress"), trigger: "change" }],
        provinceCode: [{ required: true, message: this.$t("user.pleaseEnter") + this.$t("user.province"), trigger: "change" }],
        cityCode: [{ required: true, message: this.$t("user.pleaseEnter") + this.$t("user.city"), trigger: "change" }],
      },
      errorMessage: '',
      columns: [
        {
          title: 'Recipient',
          key: 'recipientName'
        },
        {
          title: 'Detailed Address',
          slot: 'addressDetail',
        },
        {
          title: 'Operate',
          slot: 'action'
        },
      ]
    };
  },
  computed: {
    ...mapState({
      countryList: (state) => {
        let list = [];
        if (state.config.config) {
          list = state.config.config.countryList;
        }
        return list;
      },
      regionCodeList: (state) => {
        // 国际区号
        let list = [];
        if (state.config.config) {
          list = state.config.config.regionCodeList;
        }
        return list;
      },
    }),
  },
  created() {
    this.getAddressList();
  },
  methods: {
    addCreateMet() {
      this.$refs.createRef.open();
    },
    validateInput() {
      const regex = /^[0-9()\\-]*$/;
      if (!regex.test(this.formValidate.mobile)) {
        this.errorMessage = this.$t('user.input_rules_tip');
      } else {
        this.errorMessage = '';
      }
    },
    onCopy(info) {
      // 复制
      let _this = this;
      let sName = info.recipientName.split(",")[0];
      let name = info.recipientName.split(",")[1];
      let add = `${info.addressDetail} ${info.areaText} ${info.cityText} ${info.provinceText} ${info.countryText}`;
      let address = `${sName} ${name} ${add} ${info.postalCode} +${info.regionCode} ${info.mobile}`;
      this.$copyText(address).then(
        function () {
          _this.$Message.success(_this.$t("public.copySuccess"));
        },
        function () {
          _this.$Message.error(_this.$t("public.copyFail"));
        }
      );
    },
    onSetAddressDefault(id) {
      // 设置默认地址
      setAddressDefault(id).then(() => {
        this.$Message.success(this.$t("user.setSuccess"));
        this.getAddressList();
      });
    },
    onCountryAddressList(code, type) {
      // 获取
      this[type] = [];
      countryAddressList(code)
        .then((res) => {
          this[type] = res.result;
          this.gloabalLoading = false;
        })
        .catch(() => {
          this.gloabalLoading = false;
        });
    },
    onSelectCity(info) {
      this.cityList.forEach((item) => {
        if (item.id == info.value) {
          this.formValidate.postalCode = item.postalCode;
        }
      })

      // 选择市
      this.formValidate.cityText = info.label;
      this.formValidate.areaCode = "";
      this.formValidate.areaText = "";
    },
    onSelectProvince(info) {
      // 选择省份
      this.getCityList(info.value, "cityList");
      this.formValidate.provinceText = info.label;
      this.formValidate.cityCode = "";
      this.formValidate.areaCode = "";
      this.formValidate.cityText = "";
      this.formValidate.areaText = "";
    },
    getCityList(code, type) {
      // 获取
      this[type] = [];
      cityApiList(code)
        .then((res) => {
          this[type] = res.result;
          this.gloabalLoading = false;
        })
        .catch(() => {
          this.gloabalLoading = false;
        });
    },
    onCountry(value) {
      this.gloabalLoading = true;
      // 选择国家
      let info = this.countryList.find((item) => {
        return item.code == value;
      });
      this.formValidate.countryText = info.text;
      this.currentCountryImage = info.flagImg;
      this.formValidate.provinceCode = "";
      this.formValidate.cityCode = "";
      this.formValidate.areaCode = "";
      this.formValidate.provinceText = "";
      this.formValidate.cityText = "";
      this.formValidate.areaText = "";
      this.onCountryAddressList(info.code, "provinceList");
    },
    // 区号赋值
    regionChange(item) {
      let selectedOption = this.regionCodeList.find((option) => option.code + option.regionCountry === item.value);
      this.formValidate.regionCode = selectedOption.code || "";
      this.formValidate.regionCountry = selectedOption.regionCountry || "";
    },
    // 编辑
    edit(info) {
      this.$refs.createRef.open(info);
    },
    onAddressAdd() {
      // 添加地址
      this.$refs.formValidate.validate((valid) => {
        if (valid) {
          if (!this.formValidate.countryCode || !this.formValidate.provinceCode || (!this.formValidate.cityCode && this.cityList.length > 0)) {
            this.$Message.error(this.$t("user.InputAddress"));
            return;
          }
          if (!this.formValidate.surname) {
            this.$Message.error(this.$t("user.pleaseEnter") + this.$t("personal.LastName"));
            return;
          }
          if (!this.formValidate.regionCode) {
            this.$Message.error(this.$t("user.pleaseSelect") + this.$t("user.mobileAreaCode"));
            return;
          }

          this.loading = true;
          this.formValidate.recipientName = `${this.formValidate.name},${this.formValidate.surname}`;
          addressAdd(this.formValidate)
            .then((res) => {
              pointUser('actions', '2008');
              this.$Message.success(this.$t("user.addSuccessfully"));
              this.loading = false;
              this.showPop = false;
              this.getAddressList();
              this.setFormValidate();
            })
            .catch(() => {
              this.loading = false;
            });
        }
      });
    },
    hidePop() {
      // 隐藏弹窗
      this.showPop = false;
      this.setFormValidate();
    },
    setFormValidate() {
      this.currentCountryImage = "";
      this.formValidate = {
        id: "",
        surname: "", // 姓
        name: "", // 名
        addressDetail: "", // 街道地址，详细地址
        areaCode: "", // 区code
        areaText: "", // 区文本
        cityCode: "", // 市code
        cityText: "", // 市文本
        countryCode: "", // 国家编码
        countryText: "",
        districtCode: "", // 地址编码
        regionCode: "", // 手机国际区号
        isDefault: false, // 是否默认地址
        mobile: "", // 手机号
        phone: "", // 电话
        postalCode: "", // 邮政编码
        provinceCode: "",
        provinceText: "", // 省份文本
        recipientName: "", // 收件人姓名
        townText: "", // 文本
        regionCountry: "",
        regionCodeCountry: "", // 区号+国家
      };
    },
    onDeleteAddress(id) {
      // 删除地址
      deleteAddress(id).then((res) => {
        this.$Message.success(this.$t("user.deletedSuccessfully"));
        this.getAddressList();
      });
    },
    onAddressEdit() {
      // 编辑地址
      this.$refs.formValidate.validate((valid) => {
        if (valid) {
          if (!this.formValidate.countryCode || !this.formValidate.provinceCode || (!this.formValidate.cityCode && this.cityList.length > 0)) {
            this.$Message.error(this.$t("user.InputAddress"));
            return;
          }
          if (!this.formValidate.surname) {
            this.$Message.error(this.$t("user.pleaseEnter") + this.$t("personal.LastName"));
            return;
          }
          if (!this.formValidate.regionCode) {
            this.$Message.error(this.$t("user.pleaseSelect") + this.$t("user.mobileAreaCode"));
            return;
          }
          this.loading = true;
          this.formValidate.recipientName = `${this.formValidate.name},${this.formValidate.surname}`;
          addressEdit(this.formValidate)
            .then((res) => {
              this.$Message.success(this.$t("user.changeSuccessfully"));
              this.loading = false;
              this.showPop = false;
              this.getAddressList();
              this.setFormValidate();
            })
            .catch(() => {
              this.loading = false;
              this.setFormValidate();
            });
        }
      });
    },
    onDelete(id) {
      this.$Modal.confirm({
        title: this.$t("user.removeAddress"),
        content: this.$t("user.confirmDeleteAddress"),
        onOk: () => {
          this.onDeleteAddress(id);
        },
      });
    },
    getAddressList() {
      // 获取地址列表
      addressList().then((res) => {
        this.userAddressList = res.result;
      });
    },
  },
};
</script>

<style scoped lang="less">
.address-manager {
  max-width: 1200px;
  margin: 0 auto;
  // padding: 24px;

  /deep/ .ivu-table-body .ivu-table-cell {
    padding: 20px 12px;
  }


  .action-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .title {
      font-size: 24px;
      font-weight: 600;
      color: #333;
      margin: 0;
    }

    .action-buttons {
      display: flex;
      align-items: center;
      gap: 16px;

      .address-count {
        font-size: 14px;
        color: #666;
      }

      .add-button {
        height: 40px;
        padding: 0 20px;
        font-weight: 500;
      }
    }
  }

  .address-detail {
    font-size: 12px;
    color: #2F333A;
    line-height: 1.6;
    margin-bottom: 5px;
  }

  .default-tag {
    background: #FFEDF3;
    color: #FF186B;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;

  }

  .address-list {
    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 60px 0;
      background: #f9f9f9;
      border-radius: 8px;
      text-align: center;

      i {
        color: #ccc;
        margin-bottom: 16px;
      }

      p {
        color: #666;
        margin-bottom: 24px;
      }
    }

    .address-card {
      background: #fff;
      border-radius: 8px;
      padding: 24px;
      margin-bottom: 16px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      border: 1px solid #eee;
      transition: all 0.3s ease;

      &.default-address {
        border-color: #1890ff;
        background: rgba(24, 144, 255, 0.03);
      }

      &:hover {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }

      .address-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        .recipient-info {
          display: flex;
          align-items: center;
          gap: 12px;

          .recipient-name {
            font-size: 18px;
            font-weight: 500;
            color: #333;
          }


        }

        .contact-info {
          display: flex;
          align-items: center;
          gap: 12px;

          .phone {
            font-size: 14px;
            color: #666;
          }

          .postal {
            font-size: 14px;
            color: #999;
          }
        }
      }

      .address-body {
        margin-bottom: 16px;



        .address-tag {
          display: inline-block;
          background: #f0f0f0;
          color: #666;
          padding: 2px 8px;
          border-radius: 4px;
          font-size: 12px;
        }
      }

      .address-actions {
        display: flex;
        gap: 8px;

        .action-button {
          padding: 0 12px;
          height: 32px;
        }
      }
    }
  }

  .address-modal {
    .modal-content {
      padding: 16px 0;

      .country-option {
        display: flex;
        align-items: center;

        .flag {
          width: 24px;
          height: 16px;
          margin-right: 8px;
          border-radius: 2px;
        }
      }

      .region-option {
        display: flex;
        align-items: center;

        .region-flag {
          width: 24px;
          height: 16px;
          margin-right: 8px;
          border-radius: 2px;
        }
      }

      .error-message {
        color: #f5222d;
        font-size: 12px;
        margin-top: 4px;
      }
    }

    .modal-footer {
      padding: 16px 0 0;
      text-align: right;
    }

    .loading-icon {
      animation: spin 1s linear infinite;
    }

    @keyframes spin {
      from {
        transform: rotate(0deg);
      }

      to {
        transform: rotate(360deg);
      }
    }
  }
}
</style>